package com._21cn.cms.site.service;

import com._21cn.cms.common.CacheKeys;
import com._21cn.cms.common.Constants;
import com._21cn.cms.site.dao.ChannelDao;
import com._21cn.cms.site.dao.SiteDao;
import com._21cn.cms.site.entity.Channel;
import com._21cn.cms.site.entity.Site;
import com._21cn.framework.base.db.BaseDao;
import com._21cn.framework.base.service.impl.BaseServiceImpl;

import com._21cn.cms.site.dao.ColumnDao;
import com._21cn.cms.site.entity.Column;

import com._21cn.framework.cache.Cache;
import com._21cn.framework.cache.SimpleCache;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;

import java.util.HashMap;
import java.util.List;
import java.util.Map;


@Service("columnService")
public class ColumnService extends BaseServiceImpl<Column> {

    private Cache cache = new SimpleCache().init();
	
    @Autowired
    private ColumnDao columnDao;

    @Autowired
    private ChannelDao channelDao;

    @Autowired
    private SiteDao siteDao;

    @Override
    protected BaseDao<Column> getBaseDao() {
        return columnDao;
    }

    @Override
    public Column getById( Object id ) {
        Column column = super.getById( id );
        if( column == null ){
            return null;
        }
        int channelId = column.getChannelId();
        if( channelId>0 ){
            Channel channel = channelDao.selectById(channelId);
            column.setChannel(channel);
        }
        int siteId = column.getSiteId();
        if( siteId>0 ){
            Site site = siteDao.selectById(siteId);
            column.setSite(site);
        }
        return column;
    }

    public Column getColumnByUrl(String url) {
        String key = CacheKeys.columnPathKey + url;
        Column column = (Column) cache.get(key);
        if( column==null ){
            Map<String, Object> params = new HashMap<String, Object>();
            params.put("eqUrl", url);
            List<Column> columnList = getList(params, 1, 1, false);
            if( !columnList.isEmpty()){
                column = columnList.get(0);
                cache.put(key, column);
            }
        }
        return column;
    }

    public Column getColumnByPath(String path) {
        String key = "COLUMN_PATH_KEY:" + path;
        Column column = (Column)this.cache.get(key);
        if (column == null) {
            Map params = new HashMap();
            params.put("eqPath", path);
            List columnList = getList(params, 1, 1, false);
            if (!columnList.isEmpty()) {
                column = (Column)columnList.get(0);
                this.cache.put(key, column);
            }
        }
        return column;
    }
}